from tkinter import *
from tkinter import messagebox
from db_operations import DBOperations

class LoginUI:
    def __init__(self, root, on_login_success):
        self.root = root
        self.on_login_success = on_login_success
        self.db = DBOperations()
        
        self.frame = Frame(self.root, padx=20, pady=20)
        self.frame.pack(expand=True)
        
        Label(self.frame, text="用户名:").grid(row=0, column=0, sticky=W, pady=5)
        self.username_entry = Entry(self.frame)
        self.username_entry.grid(row=0, column=1, pady=5)
        
        Label(self.frame, text="密码:").grid(row=1, column=0, sticky=W, pady=5)
        self.password_entry = Entry(self.frame, show="*")
        self.password_entry.grid(row=1, column=1, pady=5)
        
        Button(self.frame, text="登录", command=self.login).grid(row=2, column=1, sticky=E, pady=10)
        
        # 设置默认账号
        self.username_entry.insert(0, "admin")
        self.password_entry.insert(0, "admin123")
    
    def login(self):
        username = self.username_entry.get()
        password = self.password_entry.get()
        
        if not username or not password:
            messagebox.showerror("错误", "用户名和密码不能为空")
            return
        
        if self.db.authenticate_user(username, password):
            self.frame.destroy()
            self.on_login_success()
        else:
            messagebox.showerror("错误", "用户名或密码错误")